using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace sforceExplorer
{
	public class frmEditList : System.Windows.Forms.UserControl
	{
		private System.Windows.Forms.DataGrid dataGrid1;
		private System.Windows.Forms.ComboBox cboObjectList;
		private System.Windows.Forms.Label label1;
		private System.Data.DataSet dataSet1;
		private System.Windows.Forms.Button btnSaveSchema;
		private System.Windows.Forms.SaveFileDialog saveFileDialog1;
		private System.Windows.Forms.Label label2;
		private System.ComponentModel.Container components = null;

		public frmEditList()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.dataGrid1 = new System.Windows.Forms.DataGrid();
			this.cboObjectList = new System.Windows.Forms.ComboBox();
			this.label1 = new System.Windows.Forms.Label();
			this.dataSet1 = new System.Data.DataSet();
			this.btnSaveSchema = new System.Windows.Forms.Button();
			this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
			this.label2 = new System.Windows.Forms.Label();
			((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();
			this.SuspendLayout();
			// 
			// dataGrid1
			// 
			this.dataGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.dataGrid1.DataMember = "";
			this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dataGrid1.Location = new System.Drawing.Point(8, 80);
			this.dataGrid1.Name = "dataGrid1";
			this.dataGrid1.Size = new System.Drawing.Size(432, 248);
			this.dataGrid1.TabIndex = 0;
			// 
			// cboObjectList
			// 
			this.cboObjectList.Location = new System.Drawing.Point(112, 16);
			this.cboObjectList.Name = "cboObjectList";
			this.cboObjectList.Size = new System.Drawing.Size(168, 21);
			this.cboObjectList.TabIndex = 1;
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(16, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(88, 16);
			this.label1.TabIndex = 2;
			this.label1.Text = "Select Object:";
			// 
			// dataSet1
			// 
			this.dataSet1.DataSetName = "NewDataSet";
			this.dataSet1.Locale = new System.Globalization.CultureInfo("en-US");
			// 
			// btnSaveSchema
			// 
			this.btnSaveSchema.Location = new System.Drawing.Point(344, 16);
			this.btnSaveSchema.Name = "btnSaveSchema";
			this.btnSaveSchema.Size = new System.Drawing.Size(96, 24);
			this.btnSaveSchema.TabIndex = 3;
			this.btnSaveSchema.Text = "Save Schema";
			this.btnSaveSchema.Click += new System.EventHandler(this.btnSaveSchema_Click);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 48);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(432, 32);
			this.label2.TabIndex = 4;
			this.label2.Text = "Edits made on this screen will be committed to your account.  Please make sure wa" +
				"nt to modify the data before editing it.";
			// 
			// frmEditList
			// 
			this.Controls.Add(this.label2);
			this.Controls.Add(this.btnSaveSchema);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.cboObjectList);
			this.Controls.Add(this.dataGrid1);
			this.Name = "frmEditList";
			this.Size = new System.Drawing.Size(448, 334);
			((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion


		private void LoadGrid(string objectName) 
		{
			try 
			{
				this.BindingContext[this.dataSet1, objectName].PositionChanged -= 
					new EventHandler(this.Binding_PositionChanged);
			} 
			catch {}
			try 
			{
				sforce.DescribeSObjectResult dsr = 
					Utility.binding.describeSObject(objectName);
				//build an empty data table
				System.Data.DataTable dt = 
					Utility.CreateDataTable(objectName, dsr);

				//build column list
				string selectList = Utility.CreateSelectList(dsr);

				this.dataGrid1.DataSource = null;
				sforce.QueryResult qr = 
					Utility.binding.query("select " + selectList + 
					" from " + objectName);
				if (qr.size > 0) 
				{
					if (dataSet1.Tables.Contains(objectName))
						Utility.LoadDataTable(qr, dataSet1.Tables[objectName]);
					else 
					{
						Utility.LoadDataTable(qr, dt);
						this.dataSet1.Tables.Add(dt);
					}
					this.dataSet1.AcceptChanges();
					this.BindingContext[this.dataSet1, objectName].PositionChanged += 
						new EventHandler(this.Binding_PositionChanged);
					this.dataGrid1.DataSource = this.dataSet1;
					this.dataGrid1.DataMember = objectName;
					Utility.CreateDataGridGridTableStyle(dataGrid1);
				} 
			}	 
			catch (Exception ex) 
			{
				System.Windows.Forms.MessageBox.Show("Error getting data." + ex.Message, 
					"Partner Sample", System.Windows.Forms.MessageBoxButtons.OK, 
					System.Windows.Forms.MessageBoxIcon.Error);
			}
		}

		private void Binding_PositionChanged(object sender, System.EventArgs e)
		{
			int oldPos = this.BindingContext[dataSet1].Position;
			System.Diagnostics.Trace.WriteLine("Binding_PositionChanged");
			try 
			{
				if (this.dataSet1.HasChanges(System.Data.DataRowState.Deleted) )
				{
					System.Data.DataSet dsDeletes = this.dataSet1.GetChanges(System.Data.DataRowState.Deleted);
					if (dsDeletes != null) 
					{
						if (System.Windows.Forms.MessageBox.Show("Are you sure you want to delete " + dsDeletes.Tables[0].Rows.Count.ToString() + " records?" + Environment.NewLine + Environment.NewLine + "(This is not reversable!!)", "VERIFY DATA DESTRUCTION", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Warning).Equals(System.Windows.Forms.DialogResult.OK))
						{
							for (int i=0;i<dsDeletes.Tables[0].Rows.Count;i++)
							{
								Utility.binding.delete(new string[] {dsDeletes.Tables[0].Rows[i]["id", System.Data.DataRowVersion.Original].ToString()});
							}
						} 
						else { dsDeletes.RejectChanges(); }
					}
				}
				if (this.dataSet1.HasChanges(System.Data.DataRowState.Modified) )
				{
					System.Diagnostics.Trace.WriteLine("Changes in dataset found.");
					System.Data.DataSet dsChanges = this.dataSet1.GetChanges(System.Data.DataRowState.Modified);
					if (dsChanges != null) 
					{
						sforce.sObject[] records = Utility.RowsToObjects(dsChanges);

						sforce.SaveResult[] sr = Utility.binding.update(records);
						for (int i=0;i<sr.Length;i++) 
						{
							if (!sr[i].success) 
							{
								System.Windows.Forms.MessageBox.Show("Error doing an update: " + sr[i].errors[0].message, "Update Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
								this.dataSet1.RejectChanges();
								this.BindingContext[dataSet1].Position = oldPos;
								return;
							}
						}
					}
				}
				dataSet1.AcceptChanges();
			} 
			catch(Exception ex) 
			{
				System.Windows.Forms.MessageBox.Show("Error doing an update: " + ex.Message, "Update Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
				this.dataSet1.RejectChanges();
				this.BindingContext[dataSet1].Position = oldPos;
			}
		}
		
		private void cboObjectList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			LoadGrid(cboObjectList.Text);
		}

		private void LoadObjectList() 
		{
			if (this.cboObjectList.Items.Count == 0) 
			{
				try 
				{
					ArrayList types = Utility.GetObjectTypes();
					for (int i=0;i<types.Count;i++)
						this.cboObjectList.Items.Add(types[i]);
					this.cboObjectList.SelectedIndex = 0;
					this.cboObjectList.SelectedIndexChanged += new System.EventHandler(this.cboObjectList_SelectedIndexChanged);
				} 
				catch(Exception ex) 
				{
					System.Windows.Forms.MessageBox.Show("Error getting object list." + System.Environment.NewLine + ex.Message, "API Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
				}
			}
		}
		public void InitialzeControl()
		{
			LoadObjectList();
		}

		private void btnSaveSchema_Click(object sender, System.EventArgs e)
		{
			if (this.saveFileDialog1.ShowDialog().Equals(System.Windows.Forms.DialogResult.OK))
			{
				this.dataSet1.WriteXmlSchema(this.saveFileDialog1.FileName);
			}
		}


	}
}
